package logic

import (
	"context"
	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"
	"edu-pro/models/mysql"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
)

type CourseDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCourseDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseDetailLogic {
	return &CourseDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CourseDetailLogic) CourseDetail(in *edurpc.CourseDetailRequest) (*edurpc.CourseDetailResponse, error) {
	//返回课程全量信息 + 讲师姓名
	var course mysql.Course
	mysql.DB.Debug().Where("id = ?", in.CourseId).Find(&course)
	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}
	var lists mysql.CourseData
	mysql.DB.Debug().Model(&mysql.Course{}).
		Select("courses.*,users.nickname").
		Joins("left join users on users.id = courses.user_id").
		Where("courses.id = ?", in.CourseId).
		Find(&lists)

	sum := 0
	count := 0
	var data []mysql.Evaluation
	mysql.DB.Debug().Where("course_id = ?", in.CourseId).Find(&data)
	for _, i := range data {
		sum += i.Score
		count++
	}
	avg := float32(sum) / float32(count)
	fmt.Println(avg)
	return &edurpc.CourseDetailResponse{
		Title:         lists.Title,
		Nickname:      lists.Nickname,
		Category:      lists.Category,
		Price:         float32(lists.Price),
		CoverUrl:      lists.CoverUrl,
		OriginalPrice: float32(lists.OriginalPrice),
		Intro:         lists.Intro,
		LearnCount:    int64(lists.LearnCount),
		Status:        int64(lists.Status),
		Avg:           avg,
	}, nil
}
